package com.usian.quartz;

import com.usian.config.RedisClient;
import com.usian.mapper.LocalMessageMapper;
import com.usian.mq.MQSender;
import com.usian.pojo.LocalMessage;
import com.usian.pojo.TbOrder;
import com.usian.service.LocalMessageService;
import com.usian.service.OrderService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;

public class OrderQuartz implements Job {

    @Autowired
    private LocalMessageService localMessageService;//本地信息记录表服务接口

    @Autowired
    private MQSender mqSender;//发送消息以及实现了comfirm（确定）回调和Return（失败）回调

    @Autowired
    private OrderService orderService;//订单服务接口

    @Value("${SETNX_LOCK_ORDER_KEY}")
    private String SETNX_LOCK_ORDER_KEY;//分布式锁key

    @Autowired
    private RedisClient redisClient;//redis工具类 二次封装了redisTemplate

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        String ip = null;
        try {
            ip = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        /* 使用redis分布式锁解决quartz 集群任务重复执行的问题 */
        if (redisClient.setnx(SETNX_LOCK_ORDER_KEY+":"+ip,"1",30)){
            //1、查询超时订单
            List<TbOrder> tbOrderList = orderService.selectOvertimeOrder();

            //2、关闭超时订单
            for (TbOrder tbOrder : tbOrderList) {
                orderService.updateOverTimeTbOrder(tbOrder);
                //3、把超时订单中的商品库存数量加回去
                orderService.updateTbItemByOrderId(tbOrder.getOrderId());
            }
            /* 定时扫描本地信息表,防止网络原因丢失数据,实现可靠消息最终一致性 */
            /* 扫描所有state为0的信息（没有发送成功的信息）   */
            List<LocalMessage> list = localMessageService.selectLocalMessageByState();
            if (list!=null && list.size()>0){
                for (LocalMessage localMessage : list) {
                    /* 重新发送 */
                    mqSender.sendMsg(localMessage);
                }
            }

            /* 删除redis分布式锁 防止死锁现象 */
            redisClient.del(SETNX_LOCK_ORDER_KEY+":"+ip);
        }else {
            System.out.println("分布式锁正在被占用");
        }

    }
}
